import { useContext, useMemo, useState, createContext } from "react";

interface DebugToolApis {
    openPanel: (content: React.ReactNode) => void;
    closePanel: () => void;
    transformChildren: (
        transformer: (children: React.ReactNode, parentStack: string[]) => React.ReactNode
    ) => void;
}

export interface DebugButtonItem {
    id: string;
    title?: string | React.ReactNode;
    icon?: React.ReactNode;
    onClick?: (helpers: DebugToolApis) => void;
    content?: React.ReactNode | ((helpers: DebugToolApis) => React.ReactNode);
    modal?: React.ReactNode | ((helpers: DebugToolApis) => React.ReactNode);
    panel?: React.ReactNode | ((helpers: DebugToolApis) => React.ReactNode);
    tooltip?: string;
    hotkey?: string;
}

interface DebugContextValue {
    buttons: DebugButtonItem[];
    registerButton: (button: Omit<DebugButtonItem, 'id'>) => string;
    unregisterButton: (id: string) => void;
}

export const useDebugButtons = () => {
    const [buttons, setButtons] = useState<DebugButtonItem[]>([]);
  
    const registerButton = (button: Omit<DebugButtonItem, 'id'>) => {
        const id = `button-${buttons.length + 1}`;
        setButtons(prev => [...prev, { ...button, id }]);
        return id;
    };
  
    const unregisterButton = (id: string) => {
        setButtons(prev => prev.filter(btn => btn.id !== id));
    };
  
    return useMemo(() => ({
        buttons,
        registerButton,
        unregisterButton,
    }), [buttons]);
};

export const DebugContext = createContext<DebugContextValue>({
    buttons: [],
    registerButton: () => '',
    unregisterButton: () => {},
});

export const useDebugContext = () => useContext(DebugContext);

export const defaultButtons:Omit<DebugButtonItem, 'id'>[] = [
    {
        context:{showBorder:true}, // 默认值
        title:({showBorder})=>{

        },
        icon:({showBorder})=>{
            if(showBorder){
                return (<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <rect x="4" y="4" width="16" height="16" rx="3" stroke="red" strokeWidth="2" />
                    <line x1="6" y1="6" x2="18" y2="18" stroke="red" strokeWidth="2" />
                </svg>)
            }else{
                return (<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                    <rect x="4" y="4" width="16" height="16" rx="3" stroke="#333" strokeWidth="2" />
                </svg>)
            }
        },
        onClick:(({transformChildren,context:{showBorder}})=>{
            transformChildren(({node,parentStack})=>{
                if (!node) return node;
                if (Array.isArray(node)) {
                    return node.map((child) => wrapWithBorder(child, parentStack));
                }
                if (isValidElement(node)) {
                    if ((node.type as any) === DevTools) return node;
                    const displayName = getDisplayName(node);
                    const newStack = [...parentStack, displayName];
                    // 只要有 data-source 就加 data-source-stack
                    const extraProps = node.props["data-source"]
                    ? { "data-source-stack": JSON.stringify(newStack) }
                    : {};
                    return (
                    <ParentStackContext.Provider value={newStack}>
                        {cloneElement(
                        node,
                        {
                            ...node.props,
                            ...extraProps,
                            style: showBorder
                            ? { border: '1px solid red', background: 'rgba(255,0,0,0.08)', position: node.props.style?.position || undefined, ...node.props.style }
                            : node.props.style
                        },
                        node.props.children ? wrapWithBorder(node.props.children, newStack) : node.props.children
                        )}
                    </ParentStackContext.Provider>
                    );
                }
                return node;
            })
        })

    }
]
